package com.example.wlzz.controller;
import com.example.wlzz.api.ConfigAPI;
import com.example.wlzz.dto.FileLocalDTO;
import com.example.wlzz.dto.UserInfoDTO;
import com.example.wlzz.entity.Category;
import com.example.wlzz.entity.Subcategory;
import com.example.wlzz.enums.Del_flagEnum;
import com.example.wlzz.enums.ResultEnum;
import com.example.wlzz.form.TaskForm;
import com.example.wlzz.repository.CategoryRepository;
import com.example.wlzz.repository.SubCategoryRepository;
import com.example.wlzz.service.TaskService;
import com.example.wlzz.service.UserInfoService;
import com.example.wlzz.service.serviceImpl.TaskServiceImpl;
import com.example.wlzz.utils.FileSaveLocalUtil;
import com.example.wlzz.utils.KeyUtil;
import com.example.wlzz.utils.ResultVOUtil;
import com.example.wlzz.vo.PageVO;
import com.example.wlzz.vo.ResultVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
@RestController
@RequestMapping("/mission")
@Slf4j
@Api(tags = "任务模块")
public class TaskController {
    @Autowired
    private ConfigAPI configAPI;
    @Autowired
    private CategoryRepository categoryRepository;   //这两块不写业务逻辑层是因为没啥逻辑好写的...
    @Autowired
    private SubCategoryRepository subCategoryRepository;
    @Autowired
    private TaskService taskService;
    @Autowired
    private TaskServiceImpl taskServiceImpl;  //主要有个同步锁，接口不能设置synchronized关键字
    @Autowired
    private UserInfoService userInfoService;
    @PostMapping("/uploadImg")
    @ApiOperation("用户上传任务图片(单张)")
    public ResultVO uploadImg(@ApiParam("提交要上传的照片")@RequestParam("file")MultipartFile file,
                             @ApiParam("token凭据") @RequestParam("token") String token) {
        try {
            String path = FileSaveLocalUtil.getYearAndMonth();   //得到路径
            String fileName = KeyUtil.genUniqueKey();
            FileSaveLocalUtil.savePic(file.getInputStream(),path,fileName);
            StringBuilder stringBuilder = new StringBuilder();
            stringBuilder.append("http://");
            stringBuilder.append(configAPI.getName());
            stringBuilder.append("/wlzzUser/getImg?");
            stringBuilder.append("flag=");
            String parameter = path+fileName;
            stringBuilder.append(URLEncoder.encode(parameter, "utf-8"));
            FileLocalDTO fileLocalDTO = new FileLocalDTO();
            List<String> list = new ArrayList<>();
            list.add(stringBuilder.toString());
            fileLocalDTO.setLocalUrl(list);
            return ResultVOUtil.success(fileLocalDTO);
        }catch (Exception e){
                e.printStackTrace();
                return ResultVOUtil.error(ResultEnum.UPLOAD_IMG_ERROR.getCode(),ResultEnum.UPLOAD_IMG_ERROR.getMessage());
        }
    }
    @PostMapping("/uploadImgs")
    @ApiOperation("用户上传任务图片(批量) Tips:文件的name值为【file】")
    public ResultVO uploadImgs(@ApiParam("token凭据") @RequestParam("token") String token,HttpServletRequest request) {
        try {
            List<MultipartFile> files =((MultipartHttpServletRequest)request).getFiles("file");
            MultipartFile file;
            FileLocalDTO fileLocalDTO = new FileLocalDTO();
            List<String> list = new ArrayList<>();
            for (int i =0;i< files.size(); ++i) {
                file = files.get(i);
                if (!file.isEmpty()) {
                    String path = FileSaveLocalUtil.getYearAndMonth();   //得到路径
                    String fileName = KeyUtil.genUniqueKey();
                    FileSaveLocalUtil.savePic(file.getInputStream(),path,fileName);
                    StringBuilder stringBuilder = new StringBuilder();
                    stringBuilder.append("http://");
                    stringBuilder.append(configAPI.getName());
                    stringBuilder.append("/wlzzUser/getImg?");
                    stringBuilder.append("flag=");
                    String parameter = path+fileName;
                    stringBuilder.append(URLEncoder.encode(parameter, "utf-8"));
                    list.add(stringBuilder.toString());
                } else {

                }
            }
            fileLocalDTO.setLocalUrl(list);
            return ResultVOUtil.success(fileLocalDTO);
        }catch (Exception e){
            e.printStackTrace();
            return ResultVOUtil.error(ResultEnum.UPLOAD_IMG_ERROR.getCode(),ResultEnum.UPLOAD_IMG_ERROR.getMessage());
        }
    }
    @PostMapping("/getCategory")
    @ApiOperation("获取主分类")
    public ResultVO getCategory(@ApiParam("token凭据") @RequestParam("token") String token) {
       List<Category> categories =  categoryRepository.findAll();
       return ResultVOUtil.success(categories);
    }
    @PostMapping("/getSubCategory")
    @ApiOperation("获取主分类下的子分类")
    public ResultVO getSubCategory(@ApiParam("token凭据") @RequestParam("token") String token,
                                    @ApiParam("主分类的id") @RequestParam("categoryId") Integer categoryId) {
        List<Subcategory> subcategories =  subCategoryRepository.findByCategoryId(categoryId);
        return ResultVOUtil.success(subcategories);
    }
    @PostMapping("/saveTask")
    @ApiOperation("保存任务（该接口已继承了图片上传）<br> 用户上传任务图片(批量) Tips:文件的name值为【file】")
    public ResultVO saveTask(@Valid TaskForm taskForm , BindingResult bindingResult,
                             @ApiParam("token凭据") @RequestParam("token") String token,
                             HttpServletRequest request) {
        if(bindingResult.hasErrors()) {
            log.warn("taskForm={}",taskForm);
            return ResultVOUtil.error(ResultEnum.TASK_ERROR.getCode(),ResultEnum.TASK_ERROR.getMessage());
        }
        ResultVO resultVO = uploadImgs(token,request);   //调用controller的批量上传接口;
        FileLocalDTO fileLocalDTO;
        if(resultVO.getCode()==0){
           fileLocalDTO = (FileLocalDTO)resultVO.getData();
        }else{
            return ResultVOUtil.error(ResultEnum.UPLOAD_IMG_ERROR.getCode(),ResultEnum.UPLOAD_IMG_ERROR.getMessage());
        }
        return taskService.save(taskForm,fileLocalDTO.getLocalUrl(),token);
    }
    @PostMapping("/getAllTask")
    @ApiOperation("获取所有人发布的任务【不分类】！")
    public ResultVO getAllTask(@ApiParam("token凭据") @RequestParam("token") String token,
                               @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                               @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        if(StringUtils.isEmpty(userInfoDTO.getSchoolName())){
            return ResultVOUtil.error(ResultEnum.SCHOOL_NAME_NULL.getCode(),ResultEnum.SCHOOL_NAME_NULL.getMessage());
        }
        PageRequest request = PageRequest.of(page,size);
        PageVO result = taskService.findAll(request,userInfoDTO.getUserId(),userInfoDTO.getSchoolName());
        return ResultVOUtil.success(result);
    }
    @PostMapping("/getCategoryTask")
    @ApiOperation("获取所有人发布的任务【只按照主分类】！")
    public ResultVO getCategoryTask(@ApiParam("token凭据") @RequestParam("token") String token,
                               @ApiParam("主分类名称(注意不是编号，是名称)") @RequestParam("category") String category,
                               @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                               @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        if(StringUtils.isEmpty(userInfoDTO.getSchoolName())){
            return ResultVOUtil.error(ResultEnum.SCHOOL_NAME_NULL.getCode(),ResultEnum.SCHOOL_NAME_NULL.getMessage());
        }
        PageRequest request = PageRequest.of(page,size);
        PageVO result = taskService.findByCategory(category,request,userInfoDTO.getUserId(),userInfoDTO.getSchoolName());
        return ResultVOUtil.success(result);
    }

    @PostMapping("/commentForTask")
    @ApiOperation("评论任务-->主评论")
    public ResultVO getCategoryTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                    @ApiParam("任务id") @RequestParam("taskId") String taskId,
                                    @ApiParam("评论内容") @RequestParam("content") String content) {
        return taskService.saveComment(token, taskId, content);
    }
    @PostMapping("/subreviewForTask")
    @ApiOperation("评论任务-->子评论")
    public ResultVO subreviewForTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                    @ApiParam("主评论id") @RequestParam("commentId") String commentId,
                                    @ApiParam("评论内容") @RequestParam("content") String content) {
        return taskService.saveSubreview(token, commentId, content);
    }
    @PostMapping("/getSelfTask")
    @ApiOperation("获取自己的发布的任务")
    public ResultVO getSelfTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                                @ApiParam("任务的状态<br>0-->未接单<br>1-->已被接单<br>2-->已完成<br>填写其他认为是全部任务") @RequestParam("status") Integer status,
                                @ApiParam("限制条数") @RequestParam("size") Integer size) {
        PageRequest request = PageRequest.of(page,size);
        ResultVO resultVO = userInfoService.getUserInfo(token);
        UserInfoDTO userInfoDTO = (UserInfoDTO)resultVO.getData();
        PageVO result;
        if(status<0|status>2){
            log.warn("填写了其他异常数字，token={}",token);
            result = taskService.getAllSelfTask(userInfoDTO.getUserId(), Del_flagEnum.EXIST.getCode(),request);
        }else{
            result = taskService.getSelfTask(userInfoDTO.getUserId(), Del_flagEnum.EXIST.getCode(),status,request);
        }
        return ResultVOUtil.success(result);
    }

    @PostMapping("/getUserTask")
    @ApiOperation("获取某个用户发布的任务")
    public ResultVO getUserTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                @ApiParam("用户id") @RequestParam("userid") Integer userid,
                                @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                                @ApiParam("限制条数") @RequestParam("size") Integer size) {
        PageRequest request = PageRequest.of(page,size);
        PageVO result = taskService.getAllSelfTask(userid, Del_flagEnum.EXIST.getCode(),request);
        return ResultVOUtil.success(result);
    }
    @PostMapping("/deleteTask")
    @ApiOperation("删除自己的任务")
    public ResultVO deleteTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
       return taskService.deleteTask(taskId,token);
    }
    @PostMapping("/getComment")
    @ApiOperation("获取评论")
    public ResultVO getComment(@ApiParam("token凭据") @RequestParam("token") String token,
                               @ApiParam("任务的id") @RequestParam("taskId") String taskId,
                               @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                               @ApiParam("限制条数") @RequestParam("size") Integer size) {
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.getCommentForTask(taskId,Del_flagEnum.EXIST.getCode(),request));
    }
    @PostMapping("/getSubreview")
    @ApiOperation("获取子评论")
    public ResultVO getSubreview(@ApiParam("token凭据") @RequestParam("token") String token,
                               @ApiParam("主评论的id") @RequestParam("commentId") String commentId,
                               @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                               @ApiParam("限制条数") @RequestParam("size") Integer size) {
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.getSubreviewForTask(commentId,Del_flagEnum.EXIST.getCode(),request));
    }

    @PostMapping("/deleteSubreview")
    @ApiOperation("删除子评论")
    public ResultVO deleteSubreview(@ApiParam("token凭据") @RequestParam("token") String token,
                                 @ApiParam("子评论的id") @RequestParam("subreviewId") String subreviewId) {

        return taskService.deleteSubreview(token,subreviewId,Del_flagEnum.EXIST.getCode());
    }
    @PostMapping("/deleteComment")
    @ApiOperation("删除主评论")
    public ResultVO deleteComment(@ApiParam("token凭据") @RequestParam("token") String token,
                                    @ApiParam("主评论的id") @RequestParam("commentId") String commentId) {
        return taskService.deleteComment(token,commentId,Del_flagEnum.EXIST.getCode());
    }

    @PostMapping("/taskRecvice")
    @ApiOperation("接受任务(接单)")
    public ResultVO taskRecvice(@ApiParam("token凭据") @RequestParam("token") String token,
                                @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
       return taskServiceImpl.receviceTask(token,taskId);
    }

    @PostMapping("/cancel_taskRecvice")
    @ApiOperation("取消已接受任务(取消接单)")
    public ResultVO cancel_taskRecvice(@ApiParam("token凭据") @RequestParam("token") String token,
                                        @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
        return taskService.cancel_taskRecvice(token,taskId);
    }

    @PostMapping("/loveTask")
    @ApiOperation("任务点赞")
    public ResultVO loveTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                       @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
        return taskService.loveTask(token,taskId);
    }
    @PostMapping("/cancel_love")
    @ApiOperation("取消任务点赞")
    public ResultVO cancel_love(@ApiParam("token凭据") @RequestParam("token") String token,
                             @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
        return taskService.cancel_love(token,taskId);
    }
    @PostMapping("/successTask")
    @ApiOperation("任务点击完成")
    public ResultVO successTask(@ApiParam("token凭据") @RequestParam("token") String token,
                             @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
        return taskService.successTask(token,taskId);
    }
    @PostMapping("/getReceiveTask")
    @ApiOperation("获取我接受的任务")
    public ResultVO getReceiveTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                   @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                                   @ApiParam("任务的状态<br>0-->放弃接单<br>1-->已接单但未完成<br>2-->已完成<br>填写其他认为是获取全部接受的任务") @RequestParam("status") Integer status,
                                   @ApiParam("限制条数") @RequestParam("size") Integer size) {
        PageRequest request = PageRequest.of(page,size);
        ResultVO resultVO = userInfoService.getUserInfo(token);
        UserInfoDTO userInfoDTO = (UserInfoDTO)resultVO.getData();
        PageVO result;
        if(status<0|status>2){
            log.warn("填写了其他异常数字，token={}",token);
            result = taskService.getAllReceiveTask(userInfoDTO.getUserId(), request);
        }else{
            result = taskService.getReceiveTask(userInfoDTO.getUserId(),status,request);
        }
        return ResultVOUtil.success(result);
    }


    @PostMapping("/taskIdForTask")
    @ApiOperation("根据任务的id获取任务详情信息")
    public ResultVO getReceiveTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                   @ApiParam("任务的id") @RequestParam("taskId") String taskId) {
        return taskService.taskIdForTask(token,taskId);
    }
    @PostMapping("/mySelfComment")
    @ApiOperation("获取别人评论我的消息")
    public ResultVO getReceiveTask(@ApiParam("token凭据") @RequestParam("token") String token,
                                  @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                                  @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.getRelated(userInfoDTO.getUserId(),request));
    }
    @PostMapping("/mySelfLove")
    @ApiOperation("获取别人点赞我")
    public ResultVO  mySelfLove(@ApiParam("token凭据") @RequestParam("token") String token,
                              @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                              @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.getLoveNotice(userInfoDTO.getUserId(),request));
    }
    @PostMapping("/aboutMeComment")
    @ApiOperation("获取我评论别人")
    public ResultVO aboutMeComment(@ApiParam("token凭据") @RequestParam("token") String token,
                                  @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                                  @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.aboutMeRelated(userInfoDTO.getUserId(),request));
    }
    @PostMapping("/aboutMeLove")
    @ApiOperation("获取我点赞了别人")
    public ResultVO aboutMeLove(@ApiParam("token凭据") @RequestParam("token") String token,
                              @ApiParam("当前页数(第0页开始)") @RequestParam("page") Integer page,
                              @ApiParam("限制条数") @RequestParam("size") Integer size) {
        UserInfoDTO userInfoDTO = (UserInfoDTO)userInfoService.getUserInfo(token).getData();
        PageRequest request = PageRequest.of(page,size);
        return ResultVOUtil.success(taskService.aboutMeLove(userInfoDTO.getUserId(),request));
    }
}
